package com.szlanyou.thirdsdk.retrofit.loading.helper;

import android.app.Activity;

import com.szlanyou.thirdsdk.retrofit.client.HttpClient;
import com.szlanyou.thirdsdk.retrofit.loading.INetLoadingManage;
import com.szlanyou.thirdsdk.retrofit.loading.NetLoadingStateAction;
import com.szlanyou.thirdsdk.retrofit.util.MyLogUtil;

import java.util.HashSet;
import java.util.Set;

/**
 * @author 陈章
 * create at 2021/7/15 10:12
 * desc:
 * 辅助开发者去快速创建Dialog形式的Loading，一个应用只有一个Loading实例。
 * 但是要求dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
 * 备注：不只是适用于网络请求{@link HttpClient}类，也适用于任何其它类似通信形式。
 */
public class AppSingleDialogLoadingHelper {
    private static final String TAG = "AppSingleDialogLoadingHelper";
    private NetLoadingStateAction loadingAction;
    private Set<INetLoadingManage> clients;
    private static AppSingleDialogLoadingHelper instance;

    private AppSingleDialogLoadingHelper() {
        clients = new HashSet<>();
    }

    public static AppSingleDialogLoadingHelper getInstance() {
        if(instance == null){
            synchronized (AppSingleDialogLoadingHelper.class){
                if(instance == null){
                    instance = new AppSingleDialogLoadingHelper();
                }
            }
        }
        return instance;
    }

    /**
     * 绑定Loading实例
     * @param netLoadingStateAction
     */
    public void bind(NetLoadingStateAction netLoadingStateAction){
        this.loadingAction = netLoadingStateAction;
    }

    /**
     * 注册需要Loading实例的对象
     * 先调用{@link #bind}方法绑定Loading框单例
     * @param netLoadingManage
     */
    public void registerHttpClient(INetLoadingManage netLoadingManage){
        if(loadingAction == null){
            throw new RuntimeException("please call bind() to bind NetLoadingStateAction,then registerHttpClient!");
        }

        if(clients.contains(netLoadingManage)){
            clients.remove(netLoadingManage);
        }
        clients.add(netLoadingManage);
    }

    /**
     * Activity退出隐藏Loading框
     */
    public void onActivityDestroy(){
        hideExistingLoading();
    }

    /**
     * 注入Loading实例到使用端
     */
    public void rejectLoadingForClients() {
        hideExistingLoading();
        for (INetLoadingManage item : clients){
            MyLogUtil.d(TAG,"reject loadingAction  + " + loadingAction + "for client " + item);
            item.setLoadingAction(loadingAction);
        }
    }

    /**
     * 关闭已经存在的Loading
     */
    private void hideExistingLoading(){
        if(loadingAction != null && loadingAction.isShowing()){
            loadingAction.hideLoading();
        }
    }

}
